package com.bitejiuyeke.job_publish.service.impl;

import com.bitejiuyeke.job_publish.common.AppResult;
import com.bitejiuyeke.job_publish.dao.MajorMapper;
import com.bitejiuyeke.job_publish.exception.ApplicationException;
import com.bitejiuyeke.job_publish.model.Major;
import com.bitejiuyeke.job_publish.service.IMajorService;
import com.bitejiuyeke.job_publish.utils.JsonUtils;
import com.bitejiuyeke.job_publish.utils.RedisUtils;
import com.bitejiuyeke.job_publish.utils.StringUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 专业相关业务接口实现类
 *
 * @Author 比特就业课
 */
@Slf4j
@Service
public class MajorServiceImpl implements IMajorService {

    @Resource
    private RedisUtils redisUtils;
    @Resource
    private MajorMapper mapper;

    private static final String KEY_MAJOR_ALL_INFO = "MAJOR:ALL:INFO";

    private static final String KEY_MAJOR_PREFIX = "MAJOR:ID:";

    // 构建KEYS
    private String buildCacheKey(Long id) {
        if (id == null) {
            throw new ApplicationException(AppResult.failed("参数不正确."));
        }
        return KEY_MAJOR_PREFIX + id;
    }

    @Override
    public List<Major> selectAllInfo() {
        List<Major> result = null;
        // 先从缓存中查询
        String content = (String) redisUtils.get(KEY_MAJOR_ALL_INFO);
        if (!StringUtils.isEmpty(content)) {
            result = JsonUtils.readListValue(content, Major.class);
            log.info("从缓存中获取全部专业信息");
            return result;
        }
        // 从数据库中查询
        result = mapper.selectAllInfo();
        if (result == null || result.size() == 0) {
            log.error("专业数据未初始化.");
            throw new ApplicationException(AppResult.failed("专业数据未初始化."));
        }
        // 写入缓存
        redisUtils.set(KEY_MAJOR_ALL_INFO, JsonUtils.writeValueAsString(result));
        log.info("从数据库中获取全部专业信息");
        return result;
    }

    @Override
    public Major selectDetailsById(Long id) {
        if (id == null || id < 1) {
            log.warn("参数校验失败, id = " + id);
            throw new ApplicationException(AppResult.failed("不是一个有效的参数"));
        }
        Major result = null;
        // 先从缓存中获取单个专业信息
        String content = (String) redisUtils.get(buildCacheKey(id));
        if (!StringUtils.isEmpty(content)) {
            result = JsonUtils.readValue(content, Major.class);
            log.info("从缓存中获取专业信息");
            return result;
        }
        // 缓存中不存在时则从数据库查询
        result = mapper.selectDetailsById(id);
        if (result != null) {
            // 写入缓存
            redisUtils.set(buildCacheKey(id), JsonUtils.writeValueAsString(result));
        }
        log.info("从数据库中获取专业信息");
        return result;
    }
}
